import React, { useState, useEffect, useCallback, FC } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { Menu, Layout } from 'antd'

import MyIconFont from '@/components/common/myIconfont'
import { getKeyName, flattenRoutes } from '@/assets/js/publicFunc'
import {getMenu} from '@/config/menu'
import logo from '@/assets/img/logo.png'
import { connect } from 'react-redux'
import * as actions from '@/store/actions'
import styles from './Menu.module.less'
const { SubMenu } = Menu
let flatMenu = []
interface Props extends ReduxProps {}
let newMenu = [];
type MenuType = CommonObjectType<string>
let dbmenu = {};
const MenuView: FC<Props> = ({ storeData: { theme, userInfo, collapsed,logoInfo } }) => {
  const { pathname } = useLocation()
  const { tabKey: curKey = 'home' } = getKeyName(pathname)
  const [current, setCurrent] = useState(curKey)
  const { permission = [] } = userInfo
  const [isGetComplete,setisGetComplete] = useState(false);
  // 递归逐级向上获取最近一级的菜单，并高亮
  const higherMenuKey = useCallback(

    (checkKey = 'home', path = pathname) => {
      const higherKey = checkKey
      if (

        checkKey === '403' ||
        flatMenu.some((item: MenuType) => item.key === checkKey)
      ) {
        return higherKey
      }
      try {
        const higherPath = path.match(/(.*)\//g)[0].replace(/(.*)\//, '$1');
      const { tabKey } = getKeyName(higherPath)
      return higherMenuKey(tabKey, higherPath)
      } catch (error) {
        console.log(error);
      }
      
    },
    [pathname]
  )
  useEffect(()=>{
    getMenu({
      // staffid:userInfo.userData.id
    }).then((res)=>{
      let data = res?.data||[];
      data.sort((a,b)=>{
        return a.sno - b.sno;
      })
      newMenu = data;
      newMenu = handleMenusData(newMenu);
      flatMenu = flattenRoutes(newMenu)
      setisGetComplete(true);
    })
  },[])
  const handleMenusData = (data)=>{
    data.map((e,i)=>{
      let key = e['menukey']+'';
      dbmenu[key] = {
        "name":e['menuname'],
        "path":e['menupath'],
        "linktype":e['menutype']
      }
      data[i]['path'] = e['menupath'];
      data[i]['name'] = e['menuname'];
      data[i]['key'] = e['menukey'];
      data[i]['linktype'] = e['menutype'];
      if(e['menutype']=='menu'){
        data[i]['type'] = 'subMenu'
      }
      if(e['children']&&e['children'].length>0){
        data[i]['routes'] = handleMenusData(e['children'])
      }
    })
    return data;
  }
  useEffect(() => {
    const { tabKey } = getKeyName(pathname)
    const higherKey = higherMenuKey(tabKey)
    setCurrent(higherKey)
  }, [higherMenuKey, pathname])

  // 菜单点击事件
  const handleClick = ({ key }): void => {
    setCurrent(key)
  }

  // 子菜单的标题
  const subMenuTitle = (data: MenuType): JSX.Element => {
    const { icon: MenuIcon, iconfont='icon-pfxinyongzhibiaoguanli' } = data
    let name = dbmenu[data.key]['name']
      return (
        <span>
          {iconfont ? (
            <MyIconFont type={iconfont} style={{ fontSize: '15px' }} />
          ) : (
            !!MenuIcon && <MenuIcon />
          )}
          <span className={styles.noselect}>{name}</span>
        </span>
      )
    if(dbmenu[data.key]){

    }else{
      return <></>
    }

  }

  // 创建可跳转的多级子菜单
  const createMenuItem = (data: MenuType): JSX.Element => {
    let menuObj = dbmenu[data.key];
    let menuItem  =  menuObj.linktype=="link"? <Menu.Item className={styles.noselect} key={data.key} title={data.name}>
        <a href={menuObj.path} target="_blank">{subMenuTitle(data)}</a>
      </Menu.Item>: <Menu.Item className={styles.noselect} key={data.key} title={data.name}>
        <Link to={'/admin'+menuObj.path}>{subMenuTitle(data)}</Link>
      </Menu.Item>
  //   let menuItem  = <Menu.Item className={styles.noselect} key={data.key} title={data.name}>
  //   <Link to={'/admin'+menuObj.path}>{subMenuTitle(data)}</Link>
  // </Menu.Item>
    return menuItem
  }

  // 创建可展开的第一级子菜单
  const creatSubMenu = (data: CommonObjectType): JSX.Element => {
    const menuItemList = []
    data.routes.map((item: MenuType) => {
    
      const arr = permission.filter((ele: MenuType) => item.key === ele.code)
      if (arr.length > 0) {
        menuItemList.push(renderMenu(item))
      }
      return arr
    })

    // const menuItemList = data.routes.reduce(
    //   (prev: any, next: any) => [...prev, renderMenu(next)],
    //   []
    // )
    return menuItemList.length > 0 ? (
      <SubMenu key={data.key} title={subMenuTitle(data)}>
        {menuItemList}
      </SubMenu>
    ) : null
  }

  // 创建菜单树
  const renderMenuMap = (list: CommonObjectType): JSX.Element[] =>
    list.map((item) => renderMenu(item))

  // 判断是否有子菜单，渲染不同组件
  function renderMenu(item: MenuType) {
    return dbmenu[item.key]?(item.type === 'subMenu' ? creatSubMenu(item) :createMenuItem(item)):<></>
  }

  const setDefaultKey = flatMenu
    .filter((item: MenuType) => item.type === 'subMenu')
    .reduce((prev: MenuType[], next: MenuType) => [...prev, next.key], [])

  const showKeys = document.body.clientWidth <= 1366 ? [] : setDefaultKey
  useEffect(()=>{
    // document.getElementById('document_title_id').innerHTML = logoInfo['title'];
    // // eslint-disable-next-line
    // document.getElementById('document_favicon_id')['href'] = window.location.origin+'/files'+logoInfo['path']
  },[logoInfo])
  return (
    <Layout.Sider
      collapsed={collapsed}
      style={{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
        userSelect: 'none'
      }}
      width={220}
    >
      <div className="logo">
        <Link to={{ pathname: '/' }}>
          <img alt="logo" src={logo} />
          {!collapsed && <h1>数仓管理平台</h1>}
        </Link>
      </div>
      <Menu
        defaultOpenKeys={showKeys}
        mode="inline"
        onClick={handleClick}
        selectedKeys={[current]}
        // theme={theme === 'default' ? 'light' : 'dark'}
      >
        
        {renderMenuMap(newMenu)}
      </Menu>
    </Layout.Sider>

  )
}

export default connect(
  (state) => state,
  actions
)(MenuView)
